import produce from "immer"
import {
  APP_SIDER_LOGO,
  APP_PRIMARY_COLOR,
  APP_ANTD_SIZE,
  APP_ANTD_LANG,
  APP_TAGS_VIEW,
  APP_SAVE_PATH,
  APP_REMOVE_PATH
} from "../actionTypes"

// 注意：如果在localStorage中找不到，则返回null
// 如果在localStorage中能找到，返回的是字符串
const fixedLogo = JSON.parse(localStorage.getItem('fixedLogo')) // 是否显示Sider上的logo
const primaryColor = localStorage.getItem('primaryColor') || '#1890ff'
const antdSize = localStorage.getItem('antdSize') || 'middle'
const lang = localStorage.getItem('lang') || navigator.language.split('-')[0] // 'zh-CN'
const showTags = JSON.parse(localStorage.getItem('showTags'))

const initState = {
  fixedLogo,
  primaryColor,
  antdSize,
  lang,
  showTags,
  historyPath: []
}

export default function (state = initState, { type, payload }) {
  return produce(state, state => {
    switch (type) {
      case APP_SIDER_LOGO:
        state.fixedLogo = !state.fixedLogo
        localStorage.setItem('fixedLogo', state.fixedLogo)
        break
      case APP_PRIMARY_COLOR:
        state.primaryColor = payload
        localStorage.setItem('primaryColor', state.primaryColor)
        break
      case APP_ANTD_SIZE:
        state.antdSize = payload
        localStorage.setItem('antdSize', payload)
        break
      case APP_ANTD_LANG:
        state.lang = payload
        localStorage.setItem('lang', payload)
        break
      case APP_TAGS_VIEW:
        state.showTags = !state.showTags
        localStorage.setItem('showTags', state.showTags)
        break
      case APP_SAVE_PATH:
        state.historyPath = payload
        break
      case APP_REMOVE_PATH:
        state.historyPath = state.historyPath.filter(item => item !== payload)
        break
      default:
        break
    }
  })
}